const { app, BrowserWindow, Menu, ipcMain, dialog, shell } = require('electron')
const path = require('node:path')
const fs = require('node:fs')
const cron = require('node-cron')
const process = require('node:process')
const os = require('node:os')
const Store = require('electron-store');
const store = new Store();

let mainWindow
function createWindow() {
  const win = new BrowserWindow({
    width: 600,
    height: 390,
    webPreferences: {
      contextIsolation: false,
      nodeIntegration: true,
      nodeIntegrationInWorker: true,
      preload: path.join(__dirname, 'preload.js')
    },
    webSecurity: false,
    maximizable: false,
    resizable: false,
    parent: String(+new Date()),
    icon: path.join(__dirname, './images/clock.ico')
  })

//  win.webContents.openDevTools()

  win.loadFile('index.html')
  return win
}

app.whenReady().then(() => {
  mainWindow = createWindow()

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow()
    }
  })
  //__dirname
  const userdir = os.homedir()
  const appUrl = app.getPath("exe")
  const lnkUrl = path.join(userdir, 'Desktop', '循环闹钟.lnk')

  //创建快捷方式
  try {
    fs.accessSync(lnkUrl)
    const res = shell.writeShortcutLink(lnkUrl, 'replace', { target: appUrl })
  } catch (error) {
    const res = shell.writeShortcutLink(lnkUrl, 'create', { target: appUrl })
  }

  mainWindow.webContents.on('did-finish-load', () => { //页面加载完再通知渲染线程
    const task_db = store.get('db')
    if (task_db && task_db.length > 0) {
      mainWindow.webContents.send('load-db', task_db)
    }

    let mp3 = store.get('clock')
    if(mp3) {
      try {
        fs.accessSync(mp3, fs.constants.R_OK); 
      } catch (error) {
        mp3 = null
      }
      if(!mp3){
        mainWindow.webContents.send('error-clock', store.get('clock'))
        store.delete('clock');
      } 
    }
  })
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

let TASKS = []
ipcMain.on('start-task', async function (event, args) {
  const uniqueArr = [...new Set(args)] //去重

  try {
    uniqueArr[0].tasks.map((value, inx) => {
      const task = cron.schedule(value, () => {
        //执行任务
        const mp3 = store.get('clock')
        event.sender.send('task-trigger', {action:'play', audio: mp3})
      },  { scheduled: false })
      TASKS.push(task)
      task.start()
    })

    event.sender.send('start-task-end', '0')
  } catch (error) {
    event.sender.send('start-task-end', '1')
  }
})

ipcMain.on('check-cron', async function(event, args){
  const v = cron.validate(args);
  event.sender.send('check-cron-end', {v: v, sc: args})
})

ipcMain.on('pause-task', async function (event, args) {
  const j = args[0]
  //暂停任务
  try {
    TASKS.map((task, inx) => {
      task.stop()
    })

    event.sender.send('task-end', '0')
  } catch (error) {
    event.sender.send('task-end', '1')
  }
})

ipcMain.on('resume-task', async function (event, args) {
  const j = args[0]
  //恢复任务
  try {
    TASKS.map((task, inx) => {
      task.start()
    })
    event.sender.send('task-end', '0')
  } catch (error) {
    event.sender.send('task-end', '1')
  }
})

ipcMain.on('destroy-task', async function (event, args) {
  const j = args[0]
  //删除任务
  try {
    TASKS.map((task, inx) => {
      task.destroyed()
    })
    event.sender.send('task-end', '0')
  } catch (error) {
    event.sender.send('task-end', '1')
  }
})

ipcMain.on('save-task', async function (event, args) {
  const uniqueArr = [...new Set(args)] //去重
  const db = uniqueArr[0].tasks

  if (db.length > 0) {
    store.set('db', db)
  }
  event.sender.send('save-task-end', db.length)
})

ipcMain.on('choise-clock', async function(event, args){
  const res = await dialog.showOpenDialogSync({
    title: '选择铃声文件！',
    defaultPath: '1.mp3',
    filters: [{ name: 'mp3|ogg|wav', extensions: ['mp3', 'ogg', 'wav'] }],
    buttonLable: '选择',
    properties: ['openFile']
  })
  if (res) {
    store.set('clock', res[0])
    event.sender.send('choise-clock-end', '1')
  }
})

const openDefaultBrowser = function (url) {
  const exec = require('child_process').exec
  switch (process.platform) {
    case 'darwin':
      exec('open ' + url);
      break;
    case 'win32':
      exec('start ' + url);
      break;
    default:
      exec('xdg-open', [url])
  }
}

ipcMain.on('open-url', async function (event, args) {
  openDefaultBrowser(args)
  //  event.sender.send('open-url-end')
})

//移除自带菜单
Menu.setApplicationMenu(null)